import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intrinsic_grid_view/intrinsic_grid_view.dart';
import 'package:live_bg_mobile/common/const/app_color_const.dart';
import 'package:live_bg_mobile/widget/ripple_card_container.dart';

import '../common/api/public_api.dart';
import '../common/type/bottom_action_sheet_type.dart';
import '../common/util/common_util.dart';
import 'bottom_action_sheet.dart';
import 'error_img.dart';

class ImgUploadList extends StatefulWidget {
  final bool imgViewerVisible;
  final double removeIconTop;
  final double removeIconRight;
  final double containerWidth;
  final double containerHeight;
  final int listColumnCount;
  final double listVerticalSpace;
  final double listHorizontalSpace;
  final double maxFileSize;
  final Icon? removeIcon;
  final Icon? selectIcon;
  final bool galleryVisible;
  final bool cameraVisible;
  final int imageQuality;
  final Function(List<String> list) onUpdateFileList;
  final List<String> fileList;

  const ImgUploadList({
    Key? key,
    required this.onUpdateFileList,
    required this.fileList,
    this.imageQuality = 60,
    this.containerHeight = 110,
    this.containerWidth = 110,
    this.imgViewerVisible = true,
    this.listColumnCount = 3,
    this.listVerticalSpace = 0,
    this.listHorizontalSpace = 5,
    this.maxFileSize = 1024,
    this.removeIconTop = 0,
    this.removeIconRight = 0,
    this.removeIcon,
    this.selectIcon,
    this.galleryVisible = true,
    this.cameraVisible = true,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => ImgUploadListState();
}

class ImgUploadListState extends State<ImgUploadList> {
  void upload(File file) {
    PublicApi.fileUpload(file).then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        widget.fileList.add(res.data["data"]);
        widget.onUpdateFileList(widget.fileList);
        setState(() {});
      } else {
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  void selectFileHandle(pickedFile) {
    var file = File(pickedFile!.path);
    var fileSize = file.lengthSync() / 1024;
    if (fileSize <= widget.maxFileSize) {
      Navigator.of(context).pop();
      upload(file);
    } else {
      CommonUtil.showToast("图片大小超过最大限制${widget.maxFileSize / 1024}M！");
    }
  }

  void removeFile(index) {
    widget.fileList.removeAt(index);
    widget.onUpdateFileList(widget.fileList);
    setState(() {});
  }

  Widget imgSelectActionSheet() {
    return BottomActionSheet(
      actionList: [
        if (widget.galleryVisible)
          BottomActionSheetItemType(
              label: "从相册添加",
              onPressed: () {
                ImagePicker()
                    .pickImage(
                  source: ImageSource.gallery,
                  imageQuality: widget.imageQuality,
                )
                    .then((pickedFile) {
                  selectFileHandle(pickedFile);
                });
              }),
        if (widget.cameraVisible)
          BottomActionSheetItemType(
              label: "拍照添加",
              onPressed: () {
                ImagePicker()
                    .pickImage(
                  source: ImageSource.camera,
                  imageQuality: widget.imageQuality,
                )
                    .then((pickedFile) {
                  selectFileHandle(pickedFile);
                });
              })
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return IntrinsicGridView.vertical(
        columnCount: widget.listColumnCount,
        verticalSpace: widget.listVerticalSpace,
        horizontalSpace: widget.listHorizontalSpace,
        children: [
          ...List.generate(
            widget.fileList.length,
            (index) => SizedBox(
              height: widget.containerHeight,
              width: widget.containerWidth,
              child: Stack(
                children: [
                  RippleCardContainer(
                    onTap: () {
                      if (widget.imgViewerVisible) {
                        CommonUtil.showImgViewer(
                            context, index, widget.fileList);
                      }
                    },
                    child: Image.network(
                      widget.fileList[index],
                      errorBuilder: (BuildContext context, Object error,
                              StackTrace? stackTrace) =>
                          const ErrorImg(),
                    ),
                  ),
                  Positioned(
                      top: widget.removeIconTop,
                      right: widget.removeIconRight,
                      child: GestureDetector(
                        onTap: () {
                          removeFile(index);
                        },
                        child: widget.removeIcon ??
                            const Icon(
                              Icons.remove_circle,
                              color: redColor,
                              size: 20,
                            ),
                      ))
                ],
              ),
            ),
          ),
          RippleCardContainer(
            onTap: () {
              showCupertinoModalPopup(
                context: context,
                builder: (BuildContext context) => imgSelectActionSheet(),
              ).then((value) {});
            },
            child: widget.selectIcon ?? const Icon(Icons.add_a_photo_outlined),
          ),
        ]);
  }
}
